package com.googlecode.jerato.library.view;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.ServletContext;

import com.googlecode.jerato.core.FunctionTransfer;
import com.googlecode.jerato.core.view.ViewTransfer;
import com.googlecode.jerato.library.logic.LogicTransferImpl;

public class ViewTransferImpl extends LogicTransferImpl implements ViewTransfer{
	public static final long serialVersionUID = ViewTransferImpl.class.hashCode();

	protected PrintWriter _writer;
	protected ByteArrayOutputStream _output;
	protected ServletContext _servletContext;
	protected StringWriter _bufferWriter = new StringWriter();

	public ViewTransferImpl(){
		_output = new ByteArrayOutputStream();
		_writer = new PrintWriter(_bufferWriter);
	}

	public ViewTransferImpl(FunctionTransfer trans){
		super(trans);
		putAll(trans);
		_output = new ByteArrayOutputStream();
		_writer = new PrintWriter(_bufferWriter);
	}
	
	public String getStringBuffer(){
		return _bufferWriter.toString();
	}

	public void println(Object obj) {
		_writer.println(obj);
	}

	public void print(Object obj) {
		_writer.print(obj);
	}

	public byte[] getCacheData() {
		_writer.flush();
		return _output.toByteArray();
	}

	public ServletContext getServletContext() {
		return _servletContext;
	}

	public void setServletContext(ServletContext context) {
		_servletContext = context;
	}

	public boolean isServletContextExists(){
		return _servletContext != null;
	}

	public void flushParent(){
		super.flushParent();
		if(_parent instanceof ViewTransfer){
			ViewTransfer parentTransfer = (ViewTransfer)_parent;
			String buffer = getStringBuffer();
			parentTransfer.print(buffer);
		}
	}
}

